package com.elegantmall.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.elegantmall.dao.OrderDao;
import com.elegantmall.pojo.OrderPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServicelmpl {

    @Autowired
    private OrderDao orderDao;

    @Transactional
    public String createOrder(String goodsId,String sellerName,int number) {
        OrderPojo order = new OrderPojo();
        String orderid = STR."G-\{System.currentTimeMillis()}";
        order.setOrderId(orderid);
        order.setGoodsId(goodsId);
        order.setSellerName(sellerName); // 默认数量1
        order.setNumber(number);
        // 创建时间由数据库自动生成
        if (order.getNumber() <= 0) {
            throw new IllegalArgumentException("商品数量必须大于0");
        }
        int result2 = orderDao.insertOrder(order);
        String result = orderid;
        return result;
    }

    public OrderPojo getOrderById(String order_id) {
        if (order_id == null || order_id.isEmpty()) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        OrderPojo order = orderDao.selectById(order_id);
        if (order == null) {
            throw new IllegalArgumentException("订单不存在");
        }
        return order;
    }

    public List<OrderPojo> getOrdersByGoodsId(String goods_id) {
        QueryWrapper<OrderPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goods_id);
        return orderDao.selectList(queryWrapper);
    }

    public List<OrderPojo> getOrdersBySellerName(String seller_name) {

        return orderDao.selectBySellerName(seller_name);
    }

    @Transactional
    public String updateOrder(OrderPojo order) {
        if (order.getOrderId() == null || order.getOrderId().isEmpty()) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        int result = orderDao.updateById(order);
        if (result == 0) {
            throw new IllegalArgumentException("订单不存在");
        }
        return "订单更新成功";
    }

    @Transactional
    public String deleteOrder(String order_id) {
        if (order_id == null || order_id.isEmpty()) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        int result = orderDao.deleteById(order_id);
        if (result == 0) {
            throw new IllegalArgumentException("订单不存在");
        }
        return "订单删除成功";
    }
}
